#include "delgroupdb.h"
#include "pg_common.h"

int main(int argc, char **argv) {
  struct group_t * groupt;
  char sql[512];
  CONNECTION_DB conn;
  PGresult *result;
  int c, force=0;
  
  groupt = (struct group_t *) malloc(sizeof(struct group_t));
  groupt->name=NULL;
  

  if(argc < 2) {
    print_help();
    exit(0);
  }

  while ( (c=getopt (argc, argv, "fh:h")) != -1 ) {
    
    switch (c) {
     
    case 'f':
      force = 1;
      break;
        
    case 'h':
      print_help();
      exit(0);
      break;

    case '?':
      break;
      
    }
    
  }
  
  if(optind < argc) {
    groupt->name = strdup(argv[optind++]);
  } else {
    printf("\n     >> Grupo nao especificado << \n\n");
    print_help();
    exit(0);
  }

  if(getuid() != 0) {
    printf("Somente o root pode executar esse comando\n");
    exit(0);
  }
  
  conn = init_db(DB_ARQ_CONF);
  if( PQstatus(conn->pgconn) != CONNECTION_OK ) {
    printf("Falha na conexao\n");
    exit(0);
  }
  
  sprintf(sql, "SELECT group_id FROM group_sys WHERE name='%s'", groupt->name);
  result = PQexec(conn->pgconn, sql);
  if(PQntuples(result)<=0) {
    printf("Grupo nao existe\n");
    free_db(conn);
    exit(0);
  }
  else{
    groupt->group_id = atoi(PQgetvalue(result,0,0));
  }
  	
  if(force==0) {
    printf("Esta operacao remove todos os usuarios do grupo %s\n", groupt->name);
    printf("Nome do grupo: %s\n", groupt->name);
    printf("GID do grupo: %d\n", groupt->group_id);

    printf("As informacoes estao corretas? [s/n] ");
    while( (c=getchar()) != 's' && c != 'n' ) {
      printf("As informacoes estao corretas? [s/n] ");
      getchar();
    }
    if(c=='n') exit(0);
    
  }
  sprintf(sql, "DELETE FROM group_sys WHERE group_id=%d", groupt->group_id);
  if(PQexec(conn->pgconn, sql)==NULL){
    printf("Erro\n");
  }
  else{
    printf("Grupo removido\n");
    /*
    int pid = fork();
    if (pid == 0){
      execlp(GROUP_CREAT, NULL,NULL);
    }
    */
  }
  PQclear(result);
  
  free_db(conn);
  return 0;

}

void print_help() {

  printf("Uso correto: delgroupdb group\n\n");
  printf("  -f		Remove grupo sem pedir confirmacao\n");
  printf("  -h		Mostra essa ajuda\n");
  printf("\nSECURE DB USERS SYSTEM MANAGEMENT\n");

}

int last_group_id(PGconn *conn) {

  PGresult *result=NULL;
  
  result = PQexec(conn, "SELECT group_id FROM group_sys ORDER BY group_id DESC LIMIT 1;");
  if( result != NULL && PQntuples(result) == 1 )
    return (atoi(PQgetvalue(result,0,0))+1);
  else
    return -1;
}

